<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta http-equiv="pragma" content="no-cache"> 
	    <meta http-equiv="Cache-Control" content="no-cache, must-revalidate"> 
	    <meta http-equiv="expires" content="0">
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
		<link rel="stylesheet" href="../css/mui.min.css" />
		<link rel="stylesheet" type="text/css" href="../css/common.css"/>
	</head>
	<style type="text/css">
		* {
			margin: 0px;
			padding: 0px;
		}
		.mui-content {
			width: 100%;
			min-width: 100%;
			height: 100%;
			background-color: #F3F3F3;
		    -webkit-overflow-scrolling: touch;
		}
		body {
			background: #F3F3F3;
			width: 100%;
			height: 100%;
			padding-bottom: 50px;
		}
		header {
			font-size: 18px;
			color: gray;
			text-align: center;
			margin: 20px;
			font-family: PingFang-SC-Regular;
		}
		.bg-herder-div {
			margin-top: 15px;
		    margin-bottom: 15px;
		    position: relative;
		    text-align: center;
		}
		.line {
			width: 92%;
			height: 1px;
			margin-left: 4%;
			margin-bottom: 5px;
			background-color: #AAAAAA;
		}
		.icon-img {
			width: 68px;
    			height: 68px;
		}
		.img-icon-bg {
		    display: inline-block;
    			vertical-align: middle;
		}
		.star-img {
			width: 10px;
			height: 10px;
			margin-right: 1px;
		}
		.star-div {
			display: inline-block;
    			vertical-align: middle;
		}
		p { 
			color: gray;
			font-size: 16px;
			font-family: PingFang-SC-Regular;
		}
		.commentsLable-bg {
			width: 100%;
		}
		.input {
			height: 30px;
			margin: 8px;
		}
		.textarea-div {
			position: relative;
		}
		textarea {
			width: 92%;
			margin-left: 4%;
			height: 133px;
			border-radius:8px ;
			font-size: 14px;
			color: #B7B7B7;
		}
		.editor-img {
			position: absolute;
		    left: 48%;
		    top: 50px;
		    width: 27px;
		    height: 23px;
		}
		.img-list {
			width: 90%;
			height:expression(this.clientWidth);
			margin-left: 4%;
			float: left;
		}
		.item-title {
			margin: 5px;
			border:1px solid #C5C5C5;
			border-radius: 15px;
			padding: 5px 15px;
			display: inline-block;
			font-size: 13px;
			font-family: "PingFang-SC-Regular";
		}
		.item-title.active{
			color: #FFFFFF;
			background-color: #013662;
		}
		span {
			color: #D0D0D0;
			font-size: 10px;
			float: right;
			position: absolute;
			left: 40%;
			bottom: 20px;
			font-family: PingFang-SC-Regular;
		}
		.upload-div {
			position: relative;
			margin-top: 15px;
		}
		.upload-img {
			float: left;
			width: 55px;
			height: 55px;
			margin-left: 4%;
			background: url(../img/evaluation/SC.png) no-repeat;
			background-size: 100% 100%;
		}
		.upload-img input::-webkit-file-upload-button {
            width: 55px;
            height: 55px;
            border: none;
            position: absolute;
            outline: 0;
            opacity: 0;
        }
        .upload-img input#file {
            display: block;
            width: auto;
            border: 0;
            vertical-align: middle;
        }
		.upload-font {
			margin-left: 40%;
			line-height: 55px;
			color: #D0D0D0;
			font-size: 10px;
			font-family: PingFang-SC-Regular;
		}
		
		.comments-img {
			margin-left: 4%;
			margin-top: 20px;
			margin-bottom: 20px;
		}
		.close-div {
			position: relative;
			display: inline-block;
			width: 18%;
			margin-right: 2%;
		}
		.img-list {
			width: 90%;
			height: 55px;
			float: left;
		}
		.close-img {
			width: 15px;
			height: 15px;
			border-radius:50% ;
			float: right;
			position: absolute;
			top: -8px;
			right: -3px;
		}
		.isChoose-span {
			display: none;
		}
		.mark-span {
			display: none;
		}
	</style>
	<body>
		<header>评 价</header>
		<div class="mui-content">
			<div class="line"></div>
			<div class="bg-herder-div">
				<div class="img-icon-bg">
					<img class="icon-img" src="../img/person/logo.png" />
				</div>
				<div class="star-div goods">
					<p >商品印记</p>
					<div id="star-img-bg"/>
						<img class="star-img goods" id = "1" src='../img/person/star.png'/>
						<img class="star-img goods" id = "2" src='../img/person/star.png'/>
						<img class="star-img goods" id = "3" src='../img/person/star.png'/>
						<img class="star-img goods" id = "4" src='../img/person/star.png'/>
						<img class="star-img goods" id = "5" src='../img/person/star.png'/>
					</div>
				</div>
			</div>	
			<div class="commentsLable-bg"></div>
			<div class="textarea-div">
				<textarea id="goodsTextId" placeholder="我有话要说："></textarea>
				<img class="editor-img goods" src="../img/address/editor.png" />
			</div>
			<div class="upload-div">
				<div class="upload-img">
					<input type="file" name="file" id="file" value="" accept="image/*" multiple onchange="handleInputChange();" />
				</div>
				<div class="upload-font">最多显示5张图片</div>
			</div>
			<div class="comments-img"></div>
			<!--返回-->
			<div class="bottom-div">
				<div class="back-div"><a class="mui-action-back" onclick="javascript:history.back(-1)"><img style="width: 10px; margin-top: 15px;" src="../img/common/back_icon.png" /></a></div>
				<div class="event-div">确 定</div>
			</div>
		</div>
	</body>
	
	<script type="text/javascript" src="../js/thirdparty/mui.min.js" ></script>
	<script type="text/javascript" src="../js/thirdparty/jquery-3.3.1.js" ></script>
	<script type="text/javascript" src="../js/thirdparty/spin.min.js" ></script>
	<script type="text/javascript" src="../js/utils/boot.js" ></script>
	<script type="text/javascript">
		var userID = base.getParameter("userID");
		var goodsID = base.getParameter("goodsID");
		var orderNo = base.getParameter("orderNo");
		var merchantID = base.getParameter("merchantID");
		var goodsStarsNo = 1; //商品的星星数量
		var technicianStarsNo = 1;//技术员的星星数量
		var tempEvalusteImgs = "";
		$(function() {
			var url = base.url.getGoodsMark;
			var data = {
				userID: userID,
				goodsID: goodsID,
				orderNo: orderNo
			};
			base.postData(url,data,getGoodsMarkDataSuccess);
		})
		function getGoodsMarkDataSuccess(data) {
			if (data.success) {
				$(".img-icon-bg .icon-img").attr("src", data.context.goodsImg);
				$(".star-div.goods p").text(data.context.goodsName);
				$(".star-div.technician p").text(data.context.technicianName);
				var tempGoodsMark = data.context.goodsMark;
				var html = "";
				for (var index in tempGoodsMark) {
					tempGoodsMark[index]["isChoose"] = 0;
					html += getArrayListItem(tempGoodsMark[index], index);
				}
				$(".commentsLable-bg").html(html);// class用.
			} else {
				mui.toast(data.msg);
			}
		}
		function getArrayListItem (item,index) {
			console.log(item.isChoose);
			var html = "";
			html += '<div class="item-title" data-index="' + index + '">'+item.markName+'<span class="isChoose-span">'+item.isChoose+'</span><span class="mark-span">'+item.markID+'</span></div>'
			return html
		}
		$(".star-img.goods").click(function(){
			goodsStarsNo = parseInt($(this).attr("id")); //parseInt()转换为字符串
			for (var i=1; i<6; i++) {
				$("#"+i).attr("src", "../img/person/star_h.png");
			}
			for (var i=1; i<goodsStarsNo+1; i++) {
				$("#"+i).attr("src", "../img/person/star.png");
			}
		})
		$(".star-img.technician").click(function(){
			technicianStarsNo = parseInt($(this).attr("id")); //parseInt()转换为字符串
			for (var i=6; i<11; i++) {
				$("#"+i).attr("src", "../img/person/star_h.png");
			}
			for (var i=6; i<technicianStarsNo+1; i++) {
				$("#"+i).attr("src", "../img/person/star.png");
			}
		})
		//为textarea注册事件，value值改变（其实是属性发生变化）时以及失去焦点时判断value值是否为空
		$('#goodsTextId').on('input propertychange blur', function() { 
		    var _this = $(this);
		    if(_this.val() == '') {
		    		$('.editor-img.goods').show();
		    } else {
	        		$('.editor-img.goods').hide();
		    }
		});
		$(".comments-img").on("tap", ".close-img", function(){
			$(this).closest(".close-div").remove();
		});
		$(".commentsLable-bg").on("tap", ".item-title", function() {
			console.log($(this).find(".isChoose-span").text());
			if ($(this).find(".isChoose-span").text() == 0) {
				$(this).find(".isChoose-span").text(1);
				$(this).attr("class", "item-title active");
			} else {
				$(this).find(".isChoose-span").text(0);
				$(this).attr("class", "item-title");
			}
		})
		function pingImgPaths(paths){
			var imgs = '<div class="close-div">'+
					   '	<img class="img-list" src="'+paths+'"/>'+
					   '	<img class="close-img" src="../img/person/close.png"/>'+
					   '</div>';
			$(".comments-img").append(imgs);		   
		}
		var fileData;//文件资源
		var imgFile = {};//文件信息
		function handleInputChange(){
			//先判断是否已有五张图片
			fileData = event.target.files[0];
			const imgMasSize = 1024 * 1024 * 5; // 5MB
			// 检查文件类型
		    if(['jpeg', 'png', 'gif', 'jpg'].indexOf(fileData.type.split("/")[1]) < 0){
		        mui.toast("文件类型仅支持 jpeg/png/gif！");
		        return;
		    }
		    // 文件大小限制
		    if(fileData.size > imgMasSize ) {
		        // 文件大小自定义限制
		        mui.toast("文件大小不能超过5MB！");
		        return;
		    }
			var imglengs = $(".comments-img").find(".close-div");
			if (imglengs.length >= 5) {
				mui.toast("最多只能上传五张图片");
				return;
			}
//			var paths = getObjectURL(fileData);
//			uploadFile(fileData);
			// 判断是否是ios
		    if(!!window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
		        // iOS
		        uploadFile(fileData);
		    } else {
		    		transformFileToDataUrl(fileData);
		    }
		}
		// 将file转成dataUrl
		function transformFileToDataUrl (file) {
		    const imgCompassMaxSize = 200 * 1024; // 超过 200k 就压缩
		
		    // 存储文件相关信息
		    imgFile.type = file.type || 'image/jpeg'; // 部分安卓出现获取不到type的情况
		    imgFile.size = file.size;
		    imgFile.name = file.name;
		    imgFile.lastModifiedDate = file.lastModifiedDate;
		
		    // 封装好的函数
		    const reader = new FileReader();
		
		    // file转dataUrl是个异步函数，要将代码写在回调里
		    reader.onload = function(e) {
		        const result = e.target.result;
		
		        if(result.length < imgCompassMaxSize) {
		            compress(result, processData, false);    // 图片不压缩
		        } else {
		            compress(result, processData, true);            // 图片压缩
		        }
		    };
		
		    reader.readAsDataURL(file);
		}
		// 使用canvas绘制图片并压缩
		function compress (dataURL, callback, shouldCompress) {
		    const img = new window.Image();
		
		    img.src = dataURL;
		
		    img.onload = function () {
		        const canvas = document.createElement('canvas');
		        const ctx = canvas.getContext('2d');
		
		        canvas.width = img.width;
		        canvas.height = img.height;
		
		        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
		
		        var compressedDataUrl;
		
		        if(shouldCompress){
		            compressedDataUrl = canvas.toDataURL(imgFile.type, 0.2);
		        } else {
		            compressedDataUrl = canvas.toDataURL(imgFile.type, 1);
		        }
		
		        callback(compressedDataUrl);
		    }
		}
		function processData (dataUrl) {
		    // 这里使用二进制方式处理dataUrl
		    const binaryString = window.atob(dataUrl.split(',')[1]);
		    const arrayBuffer = new ArrayBuffer(binaryString.length);
		    const intArray = new Uint8Array(arrayBuffer);
//		    const imgFile = this.imgFile;
		    for (var i = 0, j = binaryString.length; i < j; i++) {
		        intArray[i] = binaryString.charCodeAt(i);
		    }
		
		    const data = [intArray];
		
		    var blob;
		
		    try {
		        blob = new Blob(data, { type: imgFile.type });
		    } catch (error) {
		        window.BlobBuilder = window.BlobBuilder ||
		            window.WebKitBlobBuilder ||
		            window.MozBlobBuilder ||
		            window.MSBlobBuilder;
		        if (error.name === 'TypeError' && window.BlobBuilder){
		            const builder = new BlobBuilder();
		            builder.append(arrayBuffer);
		            blob = builder.getBlob(imgFile.type);
		        } else {
		            mui.toast("版本过低，不支持图片压缩");
		            throw new Error('版本过低，不支持上传图片');
		        }
		    }
		
		    // blob 转file
		    const fileOfBlob = new File([blob], imgFile.name);
		    uploadFile(fileOfBlob)
		}
		
		//上传图片
		function uploadFile(imgfile){
//			base.setWait("正在上传...");
			mui.toast("正在上传，请稍等...");
			var formData = new FormData();
			formData.append('file', imgfile);
	//		formData.append('myfile', $('input[name=file]')[0].files[0]);
			$.ajax({
	            url: base.url.uploadFile,
	            method: 'POST',
	            data: formData,
	            contentType: false, // 注意这里应设为false
	            processData: false,
	            cache: false,
	            success: function(data) {
//	            	base.clearWait();
	            	data = JSON.parse(data);
	            	pingImgPaths(data.obj);
	            },
	            error: function (jqXHR) {
//	            	base.clearWait();
	                console.log(JSON.stringify(jqXHR));
	            }
	        })
		}
		//建立一個可存取到該file的url
		function getObjectURL(file) {
			var url = null ;
			if (window.createObjectURL!=undefined) { // basic
				url = window.createObjectURL(file);
			} else if (window.URL!=undefined) { // mozilla(firefox)
				url = window.URL.createObjectURL(file);
			} else if (window.webkitURL!=undefined) { // webkit or chrome
				url = window.webkitURL.createObjectURL(file);
			}
			return url;
		}
		$('.bottom-div').on('tap', '.event-div', function() {
			var markIds = "";
			$(".commentsLable-bg").find(".item-title").each(function() { 
		        var isChoose = $(this).find('span[class*=isChoose-span]').text();
		        var markID = $(this).find('span[class*=mark-span]').text();
		        if(isChoose == 1) {
		        		markIds += markID;
		        		markIds += ",";
		        }
		    });
		    markIds = markIds.substring(0, markIds.length-1);
		    tempEvalusteImgs = tempEvalusteImgs.substring(0, tempEvalusteImgs.length-1);
		    var url = base.url.evaluateGoods;
			var data = { 
				userID: userID,
				goodsID: goodsID,
				merchantID: merchantID,
				goodsStars: goodsStarsNo,
				markIds: markIds,
				goodsContent: $("#goodsTextId").val(),
				orderNo: orderNo,
				evalusteImgs: tempEvalusteImgs
			};
			base.postData(url,data,evaluateGoodsDataSuccess);
		})
		function evaluateGoodsDataSuccess(data) {
			if (data.success) {
				setTimeout(function(){
					mui.toast(data.msg);
				},2000);
				mui.back();
			} else {
				mui.toast(data.msg);
			}
		}
	</script>
</html>
